import { useEffect, useRef, useState } from 'react'
import { ScrollNavbarType, tabsType } from '../..'

export default function ScrollNavbar(props: ScrollNavbarType) {
    const {
        height = 40,
        tabs = [],
        activeKey = 0,
        themeColor = '#1990b4',
        fixedStart = true,
        right,
        rightClass = '',
        tail,
        offsetTop = 0,
        isSticky = true,
        fontSize = 16,
        itemGap = 32,
        activeLineOffsetTop = 0,
        scrollOffsetLeft = 0,
        onChange,
        onRightClick,
    } = props
    // 元素滚动距离
    const [scrollLeft, setScrollLeft] = useState(0)
    // 滚动盒子
    let scrollBox = useRef<any>(null)
    // 获取有效的激活索引
    const getActiveKey = (key: number) => {
        if (!key || key < 0) return 0
        if (key >= tabs.length) return tabs.length - 1
        return key
    }
    const [_activeKey, setActiveKey] = useState<number>(0)

    // 点击滚动
    const handleClick = (index: number, item: tabsType | string) => {
        setActiveKey(index)
        scrollFun(scrollBox.current, index)
        onChange && onChange(index, item)
    }

    // 元素滚动
    const scrollChange = (e: any) => {
        setScrollLeft(Number(scrollBox?.current?.scrollLeft))
    }

    // 滚动方法
    const scrollFun = (scrollBox: any, index: number = 0) => {
        // 需要滚动的距离
        let sumWidth = 0
        // 所有列表
        const list = document.querySelectorAll('.list-item')
        if (list.length === 0) return
        // 视口宽度的一半
        const bodyWidth = document.body.clientWidth / 2
        // 这个元素宽度的一半
        const thisElWidth = list[index].clientWidth / 2
        list.forEach((item, i) => {
            if (i < index) {
                sumWidth += item.clientWidth
            }
        })
        // 计算滚动距离
        const distance = sumWidth - bodyWidth + thisElWidth - scrollOffsetLeft
        // 滚动
        scrollBox?.scrollTo(distance, 0)
    }

    useEffect(() => {
        setActiveKey(getActiveKey(activeKey))
        scrollBox.current = document.querySelector('#scroll-box')
        scrollBox?.current?.addEventListener('scroll', scrollChange, true)
        scrollFun(scrollBox.current, getActiveKey(activeKey))
        return () => {
            scrollBox.current?.removeEventListener('scroll', scrollChange, true)
        }
    }, [activeKey])

    // 列表元素动态类名
    const itemClassName = (index: number) => {
        let str = 'list-item'
        if (index === _activeKey) {
            str += ' active'
        }
        if (fixedStart && index === 0 && scrollLeft > 5) {
            str += ' fixation'
        }
        return str
    }

    // 样式
    const style = {
        '--height': height + 'px',
        '--bottom': -activeLineOffsetTop + 'px',
        '--color': themeColor,
        '--offsetTop': offsetTop + 'px',
        '--position': isSticky ? 'sticky' : 'static',
        '--fontSize': fontSize + 'px',
        '--itemGap': (itemGap / 2) + 'px',
    } as React.CSSProperties

    return (
        <div className="scroll-bar" style={style}>
            <ul className="list" id="scroll-box">
                {tabs.map((item: tabsType | string, index: number) => {
                    return (
                        <li className={itemClassName(index)} key={index} onClick={() => handleClick(index, item)}>
                            <span>{ typeof item === 'string' ? item : item.lable}</span>
                        </li>
                    )
                })}
                {tail && tail}
            </ul>
            {right && (
                <div className={'right ' + rightClass} onClick={onRightClick}>
                    {right}
                </div>
            )}
        </div>
    )
}
